#!/bin/bash
DATA_DIR="/var/lib/mongo/config/data"
PID_DIR="/var/run/mongodb"
CONF_DIR="/etc/mongod/conf.d"
LOG_DIR="/var/log/mongodb"
BIND_IP=$(ifconfig eth0|grep inet|grep -v inet6|awk '{print $2}')
#
[ ! -d ${DATA_DIR} ] && mkdir -p ${DATE_DIR}
[ ! -d ${PID_DIR} ] && mkdir -p ${PID_DIR}
[ ! -d ${CONF_DIR} ] && mkdir -p ${CONF_DIR}
[ ! -d ${LOG_DIR} ] && mkdir -p ${LOG_DIR}

/usr/bin/chown -R mongod.mongod ${PID_DIR}
/usr/bin/chown -R mongod.mongod ${LOG_DIR}
/usr/bin/chown -R mongod.mongod /var/lib/mongo

#配置firewalld防火墙
#firewall-cmd --add-port=22000/tcp --permanent
#firewall-cmd --add-port=22000/tcp
systemctl stop firewalld
setenforce 0
#添加配置文件config.conf
cd ${CONF_DIR}
[ ! -f config.conf ] && \
cat >>config.conf <<EOF
systemLog:
  destination: file
  logAppend: true
  path: ${LOG_DIR}/configsrv.log
storage:
  dbPath: ${DATA_DIR}
  journal:
    enabled: true
processManagement:
  fork: true
  pidFilePath: ${PID_DIR}/configsvr.pid
  timeZoneInfo: /usr/share/zoneinfo
net:
  port: 22000
  bindIp: ${BIND_IP}
  maxIncomingConnections: 30000
replication:
  replSetName: csReplSet
sharding:
  clusterRole: configsvr
EOF
OPTIONS="-f /etc/mongod/conf.d/config.conf"
cd /usr/lib/systemd/system 
[ ! -f mongod-configsvr.service ] && \
cat >>mongod-configsvr.service <<EOF
[Unit]
Description=Mongodb Config Server
After=network.target
Documentation=https://docs.mongodb.org/manual

[Service]
User=mongod
Group=mongod
Environment="OPTIONS=-f ${CONF_DIR}/config.conf"
ExecStart=/usr/bin/mongod $OPTIONS
ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb
ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb
ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb
PermissionsStartOnly=true
PIDFile=${PID_DIR}/configsvr.pid
Type=forking
# file size
LimitFSIZE=infinity
# cpu time
LimitCPU=infinity
# virtual memory size
LimitAS=infinity
# open files
LimitNOFILE=64000
# processes/threads
LimitNPROC=64000
# locked memory
LimitMEMLOCK=infinity
# total threads (user+kernel)
TasksMax=infinity
TasksAccounting=false
# Recommended limits for for mongod as specified in
# http://docs.mongodb.org/manual/reference/ulimit/#recommended-settings
[Install]
WantedBy=multi-user.target
EOF
#启动服务
cd ${DATA_DIR} && [ ! -f mongod.lock ] && rm -rf mongod.lock
systemctl enable mongod-configsvr
systemctl daemon-reload
systemctl start mongod-configsvr
if [ "`ss -tunlp|grep 22000|cut -d: -f2|awk '{print $1}'`" == "22000" ];then
	echo "mongod-configsvr start succfull"
else
	echo "mongod-configsvr start fail"
	exit 1
fi
#配置初始化副本集(只要在一台电脑上配置即可)
/usr/bin/mongo ${BIND_IP}:22000 <<EOF
config = { _id:"csReplSet",members:[ {_id:1,host:"10.2.13.187:22000"},{_id:2,host:"10.2.13.186:22000"},{_id:3,host:"10.2.13.185:22000"}] }
rs.initiate(config)
EOF


